package com.example.demo.controller;

import com.example.demo.annotation.RepeatForm;
import com.example.demo.entity.Comment;
import com.example.demo.entity.Question;
import com.example.demo.entity.User;
import com.example.demo.service.impl.CommentServiceImpl;
import com.example.demo.service.impl.QuestionServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ak
 * @since 2020-03-30
 */
@Controller
@Slf4j
public class QuestionController {
    @Autowired
    QuestionServiceImpl questionService;
    @Autowired
    CommentServiceImpl commentService;

    @GetMapping("getQuestionList")
    public String getQuestionList(Model model) {
        return "index";
    }

    @PostMapping("search")
    public String search(String search){
        return "forum";
    }

    @GetMapping("publish")
    public String publish(){
        return "publish";
    }

    @RepeatForm
    @PostMapping("publishQuestion")
    public String publishQuestion(@Valid Question question,HttpServletRequest request,BindingResult result){
        if (result.hasErrors()){
            String message = result.getFieldError().getDefaultMessage();
            request.setAttribute("msgError",message);
            return "publish";
        }
        questionService.saveQuestion(question);
        request.setAttribute("question",question);
        return "redirect:/question/"+question.getQId();
    }

    @RepeatForm
    @GetMapping("question/{id}")
    public ModelAndView getQuestion(@PathVariable Integer id){
        Question question = questionService.getQuestion(id);
        List<Comment> commentList = commentService.getCommentList(id);
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("question",question);
        modelAndView.addObject("user", user);
        modelAndView.addObject("commentList",commentList);
        modelAndView.setViewName("question");
        return modelAndView;
    }
}
